// 观察者接口
interface Observer {
  update(message: string): void;
}

// 具体观察者
class ConcreteObserver implements Observer {
  private name: string;

  constructor(name: string) {
    this.name = name;
  }

  update(message: string): void {
    console.log(`${this.name} 收到消息: ${message}`);
  }
}

// 主题（被观察者）接口
interface Subject {
  attach(observer: Observer): void;
  detach(observer: Observer): void;
  notify(message: string): void;
}

// 具体主题
class ConcreteSubject implements Subject {
  private observers: Observer[] = [];

  attach(observer: Observer): void {
    if (!this.observers.includes(observer)) {
      this.observers.push(observer);
    }
  }

  detach(observer: Observer): void {
    this.observers = this.observers.filter(obs => obs !== observer);
  }

  notify(message: string): void {
    this.observers.forEach(observer => observer.update(message));
  }
}

// 使用示例
const subject = new ConcreteSubject();

const observer1 = new ConcreteObserver('观察者A');
const observer2 = new ConcreteObserver('观察者B');

subject.attach(observer1);
subject.attach(observer2);

subject.notify('第一次通知');

subject.detach(observer1);

subject.notify('第二次通知');

export {ConcreteObserver, ConcreteSubject}